package com.xuecheng.content.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author shiminghui
 * @date 2024/8/1 9:45
 * @description: TODO
 */
@Service
@RequiredArgsConstructor
public class CourseBaseInfoServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseInfoService {

    private final CourseMarketMapper courseMarketMapper;
    private final TeachplanMapper teachplanMapper;
    private final TeachplanMediaMapper teachplanMediaMapper;
    private final CourseTeacherMapper courseTeacherMapper;
    private final CourseCategoryMapper courseCategoryMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(String companyId, PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {

        //创建分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //拼接查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(StringUtils.isNotBlank(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName())
                .eq(StringUtils.isNotBlank(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus())
                .eq(StringUtils.isNotBlank(companyId), CourseBase::getCompanyId, companyId)
                .eq(StringUtils.isNotBlank(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());
        //获取查询结果
        page = page(page, queryWrapper);

        PageResult<CourseBase> pageResult = new PageResult<>(page.getRecords(), page.getTotal(), pageParams.getPageNo(), pageParams.getPageSize());

        return pageResult;
    }

    @Override
    public CourseBaseInfoDto addCourse(Long companyId, AddCourseDto addCourseDto) {
        //合法性校验
        if (StringUtils.isBlank(addCourseDto.getName())) {
            throw new XueChengPlusException("课程名称为空");
        }

        if (StringUtils.isBlank(addCourseDto.getMt())) {
            throw new XueChengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(addCourseDto.getSt())) {
            throw new XueChengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(addCourseDto.getGrade())) {
            throw new XueChengPlusException("课程等级为空");
        }

        if (StringUtils.isBlank(addCourseDto.getTeachmode())) {
            throw new XueChengPlusException("教育模式为空");
        }

        if (StringUtils.isBlank(addCourseDto.getUsers())) {
            throw new XueChengPlusException("适应人群为空");
        }

        if (StringUtils.isBlank(addCourseDto.getCharge())) {
            throw new XueChengPlusException("收费规则为空");
        }

        //将课程基本信息存入数据库
        CourseBase courseBase = BeanUtil.copyProperties(addCourseDto, CourseBase.class);
        if (courseBase != null) {
            courseBase.setCompanyId(companyId);//机构id
            courseBase.setCreateDate(LocalDateTime.now());//创建时间
            courseBase.setAuditStatus("202002");//审核状态
            courseBase.setStatus("203001");//发布状态
        }
        boolean save = save(courseBase);
        if (!save) {
            throw new XueChengPlusException("课程基本信息插入失败");
        }

        //将课程营销信息存入数据库
        CourseMarket courseMarket = new CourseMarket();
        BeanUtil.copyProperties(addCourseDto, courseMarket);
        courseMarket.setId(courseBase.getId());
        if (saveCourseMarket(courseMarket) <= 0) {
            throw new XueChengPlusException("保存营销信息失败");
        }

        return getCourseBaseInfo(courseBase.getId());
    }

    //获取课程信息
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long id) {
        CourseBase courseBase = getById(id);
        if (courseBase == null) {
            return null;
        }
        //拼接返回对象
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtil.copyProperties(courseBase, courseBaseInfoDto);
        BeanUtil.copyProperties(courseMarket, courseBaseInfoDto);

        //查询分类名称
        CourseCategory Mt = courseCategoryMapper.selectById(courseBase.getMt());
        if (Mt != null) {
            courseBaseInfoDto.setMtName(Mt.getName());
        }
        CourseCategory St = courseCategoryMapper.selectById(courseBase.getSt());
        if (St != null) {
            courseBaseInfoDto.setStName(St.getName());
        }

        return courseBaseInfoDto;
    }

    @Override
    public CourseBaseInfoDto updateCourse(Long companyId, EditCourseDto editCourseDto) {
        //课程id
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = getById(courseId);
        if (courseBase == null) {
            XueChengPlusException.cast("课程不存在");
        }

        //校验本机构只能修改本机构的课程(机构id后续拿到先写死)TODO
        if (!courseBase.getCompanyId().equals(companyId)) {
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        BeanUtil.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
//        courseBase.setChangePeople();TODO
        boolean b = updateById(courseBase);
        if (!b) {
            throw new XueChengPlusException("修改课程表失败");
        }
        CourseMarket courseMarket = BeanUtil.copyProperties(editCourseDto, CourseMarket.class);
        int i = saveCourseMarket(courseMarket);
        if (i <= 0) {
            throw new XueChengPlusException("修改课程营销信息失败");
        }

        return getCourseBaseInfo(courseBase.getId());
    }

    /**
     * 删除课程信息
     *
     * @param id
     */
    @Override
    public void deleteCourseBaseInfo(Long id) {
        //判断其是否为未提交状态
        CourseBase courseBase = getById(id);
        if (courseBase == null) {
            throw new XueChengPlusException("课程信息不存在");
        }
        if (!courseBase.getAuditStatus().equals("202002")) {
            throw new XueChengPlusException("仅课程审核状态为未提交的可以删除");
        }
        //删除课程信息
        boolean b = removeById(id);
        if (!b) {
            throw new XueChengPlusException("删除课程信息失败");
        }
        //删除课程营销信息
        LambdaQueryWrapper<CourseMarket> marketLambdaQueryWrapper = new LambdaQueryWrapper<>();
        marketLambdaQueryWrapper.eq(CourseMarket::getId, id);
        Integer i = courseMarketMapper.selectCount(marketLambdaQueryWrapper);
        if (i != 0) {
            int delete = courseMarketMapper.delete(marketLambdaQueryWrapper);
            if (delete <= 0) {
                throw new XueChengPlusException("删除课程营销信息失败");
            }
        }
        //删除课程计划
        LambdaQueryWrapper<Teachplan> teachplanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanLambdaQueryWrapper.eq(Teachplan::getCourseId, id);
        Integer i1 = teachplanMapper.selectCount(teachplanLambdaQueryWrapper);
        if (i1 != 0) {
            int delete1 = teachplanMapper.delete(teachplanLambdaQueryWrapper);
            if (delete1 <= 0) {
                throw new XueChengPlusException("删除课程计划失败");
            }
        }
        //删除媒资信息
        LambdaQueryWrapper<TeachplanMedia> mediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        mediaLambdaQueryWrapper.eq(TeachplanMedia::getCourseId, id);
        Integer i2 = teachplanMediaMapper.selectCount(mediaLambdaQueryWrapper);
        if (i2 != 0) {
            int delete2 = teachplanMediaMapper.delete(mediaLambdaQueryWrapper);
            if (delete2 <= 0) {
                throw new XueChengPlusException("删除媒资信息失败");
            }
        }
        //删除师资信息
        LambdaQueryWrapper<CourseTeacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherLambdaQueryWrapper.eq(CourseTeacher::getCourseId, id);
        Integer i3 = courseTeacherMapper.selectCount(teacherLambdaQueryWrapper);
        if (i3 != 0) {
            int delete3 = courseTeacherMapper.delete(teacherLambdaQueryWrapper);
            if (delete3 <= 0) {
                throw new XueChengPlusException("删除师资信息失败");
            }
        }
    }

    //保存营销信息
    private int saveCourseMarket(CourseMarket courseMarket) {
        //收费规则
        String charge = courseMarket.getCharge();
        if (StringUtils.isBlank(charge)) {
            throw new XueChengPlusException("收费规则没有选择");
        }
        //收费规则为收费
        if (charge.equals("201001")) {
            if (courseMarket.getPrice() == null || courseMarket.getPrice().floatValue() <= 0) {
                throw new XueChengPlusException("课程为收费价格不能为空且必须大于0");
            }
        }
        //根据id从课程营销表查询
        CourseMarket courseMarketObj = courseMarketMapper.selectById(courseMarket.getId());
        if (courseMarketObj == null) {
            return courseMarketMapper.insert(courseMarket);
        } else {
            BeanUtils.copyProperties(courseMarket, courseMarketObj);
            courseMarketObj.setId(courseMarket.getId());
            return courseMarketMapper.updateById(courseMarketObj);
        }
    }
}
